<template>
  <div class="table-box">
    <div class="card table-search">
      <el-form ref="formRef" :model="searchParam">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="在线状态：">
              <el-select v-model="searchParam.state_list" @change="search">
                <el-option v-for="(item, index) of statusData" :key="index" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账号分组：">
              <el-select v-model="searchParam.group_list" @change="search">
                <el-option v-for="(item, index) of accountData" :key="index" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账号类别：">
              <el-select v-model="searchParam.type_list" @change="search">
                <el-option v-for="(item, index) of accountType" :key="index" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="card table-main">
      <div class="table-header">
        <div class="header-button-lf">
          <el-button type="primary" :icon="Plus" @click="addAccount">添加云手机</el-button>
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="phoneIp" label="IP地址" align="center" />
        <el-table-column prop="accountState" label="在线状态" align="center" />
        <el-table-column prop="accountName" label="账号昵称" align="center" />
        <el-table-column prop="phoneGroup" label="组别名称" align="center" />
        <el-table-column prop="phoneName" label="所在云手机名称" align="center" />
        <el-table-column prop="mmId" label="微信id" align="center" />
        <el-table-column prop="accountType" label="账号类型" align="center" />
        <el-table-column label="操作" width="420" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" :icon="Refresh" @click="reLink(scope.row)">重连</el-button>
            <el-button type="danger" size="small" :icon="Comment" :disabled="!scope.row.friendNotPassWarning">提醒</el-button>
            <el-button type="primary" size="small" :icon="Tickets" @click="toDetail(scope.row)">详情</el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="deleteItem(scope.row)">删除</el-button>
            <el-button type="primary" size="small" :icon="Edit" @click="editItem(scope.row)">编辑分组</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <div class="table-empty">
            <slot name="empty">
              <img src="@/assets/images/notData.png" alt="notData" />
              <div>暂无数据</div>
            </slot>
          </div>
        </template>
      </el-table>

      <el-pagination
        background
        layout="prev, pager, next, total"
        :total="total"
        v-model:current-page="query.page"
        v-model:page-size="query.size"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="500"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <el-form :model="accountForm" :rules="accountRules" ref="accountFormRef" label-width="100">
        <el-form-item label="用户ip" prop="phoneIp">
          <el-input v-model="accountForm.phoneIp" placeholder="请输入ip" :disabled="!!accountForm.accountId"></el-input>
        </el-form-item>
        <el-form-item label="手机名称" prop="phoneName">
          <el-input v-model="accountForm.phoneName" placeholder="请输入手机名称" :disabled="!!accountForm.accountId"></el-input>
        </el-form-item>
        <el-form-item label="手机分组" prop="phoneGroup">
          <el-input v-model="accountForm.phoneGroup" placeholder="请输入手机分组"></el-input>
        </el-form-item>
        <el-form-item label="版本号" prop="mmVersion">
          <el-select v-model="accountForm.mmVersion">
            <el-option v-for="item of versionList" :key="item" :label="item" :value="item" placeholder="请选择版本号"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="detailVisible" title="详情" :close-on-click-modal="false">
      <div class="table-detail">
        <RecordComp v-if="detailVisible" :account-id="accountId" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="accountManagement">
import { ref } from "vue";
import { Edit, Delete, Plus, Comment, Tickets, Refresh } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addPhoneApi,
  deletePhoneApi,
  updateAccountGroupApi,
  getAccountListApi,
  getAccountTypesApi,
  getAccountGroupsApi,
  getAccountStatesApi,
  versionApi,
  reconnectPhoneApi
} from "@/api/modules/business";
import { AccountList } from "@/api/interface";
import RecordComp from "./record.vue";

const formRef = ref<any>();
const searchParam = ref({
  state_list: "全部",
  group_list: "全部",
  type_list: "全部"
});
const statusData = ref<{ name: string }[]>([]);
const accountData = ref<{ name: string }[]>([]);
const accountType = ref<{ name: string }[]>([]);
const tableData = ref<AccountList[]>([]);
const total = ref(0);
const query = ref({ page: 1, size: 10 });
const dialogVisible = ref(false);
const title = ref("添加云手机");
const accountFormRef = ref<any>();
const accountForm = ref<Record<string, any>>({
  accountId: "",
  phoneIp: "",
  phoneName: "",
  phoneGroup: "",
  mmVersion: ""
});
const accountRules = {
  phoneIp: { required: true, message: "请输入ip", trigger: "blur" },
  phoneName: { required: true, message: "请输入手机名称", trigger: "blur" },
  phoneGroup: { required: true, message: "请输入手机分组", trigger: "blur" },
  mmVersion: { required: true, message: "请选择版本号", trigger: "blur" }
};
const detailVisible = ref(false);
const accountId = ref("");
const versionList = ref<string[]>([]);

function search() {
  query.value.page = 1;
  getAccountData();
}

function addAccount() {
  title.value = "添加云手机";
  dialogVisible.value = true;
}

function handleClose() {
  dialogVisible.value = false;
  accountForm.value = {};
  accountFormRef.value.resetFields();
}

function handleConfirm() {
  accountFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const params = {
        ip: accountForm.value.phoneIp,
        phoneName: accountForm.value.phoneName,
        phoneGroup: accountForm.value.phoneGroup,
        mmVersion: accountForm.value.mmVersion
      };
      const data = accountForm.value.accountId
        ? await updateAccountGroupApi({
            accountId: accountForm.value.accountId,
            accountGroup: accountForm.value.phoneGroup,
            mmVersion: accountForm.value.mmVersion
          })
        : await addPhoneApi(params);
      if (data.result) {
        handleClose();
        await getAccountData();
        ElMessage.success(data.message || "操作成功");
      } else {
        ElMessage.error(data.message);
      }
    }
  });
}

function editItem(row: Record<string, any>) {
  title.value = "编辑分组";
  accountForm.value = { ...row };
  dialogVisible.value = true;
}

function reLink(row: Record<string, any>) {
  console.log(row);
  ElMessageBox.confirm(`确认重连 ip${row.phoneIp} 云手机？`, "重连", {
    confirmButtonText: "确认",
    type: "warning",
    closeOnClickModal: false,
    closeOnPressEscape: false
  }).then(async () => {
    const data = await reconnectPhoneApi(row.accountId);
    if (!data.result) return ElMessage({ type: "error", message: data.message });
    ElMessage({ type: "success", message: "重连成功" });
    await getAccountData();
  });
}

function toDetail(row: Record<string, any>) {
  detailVisible.value = true;
  accountId.value = row.accountId || "";
}

function deleteItem(row: Record<string, any>) {
  ElMessageBox.confirm(`确认删除 ip为${row.phoneIp} 这条数据？`, "删除", {
    confirmButtonText: "确认",
    type: "warning",
    closeOnClickModal: false,
    closeOnPressEscape: false
  }).then(async () => {
    const data = await deletePhoneApi(row.phoneIp);
    if (!data.result) return ElMessage({ type: "error", message: data.message });
    ElMessage({ type: "success", message: "删除成功" });
    await getAccountData();
  });
}

async function getAccountTypes() {
  const data = await getAccountTypesApi();
  accountType.value = data.typeList.map(item => {
    return { name: item };
  });
}

async function getAccountGroups() {
  const data = await getAccountGroupsApi();
  accountData.value = data.groupList.map(item => {
    return { name: item };
  });
}

async function getAccountStates() {
  const data = await getAccountStatesApi();
  statusData.value = data.stateList.map(item => {
    return { name: item };
  });
}

async function getVersion() {
  const data = await versionApi();
  console.log(data);
  if (data.result) versionList.value = data.versionList || [];
}

async function getAccountData() {
  const data = await getAccountListApi({
    ...query.value,
    with_messages: true,
    ...searchParam.value
  });
  tableData.value = data.data || [];
  total.value = data.total || 0;
}

function handleSizeChange(num: number) {
  query.value.page = 1;
  query.value.size = num;
  getAccountData();
}

function handleCurrentChange(num: number) {
  query.value.page = num;
  getAccountData();
}

getVersion();
getAccountTypes();
getAccountGroups();
getAccountStates();
getAccountData();
</script>

<style scoped lang="scss">
@import "./index";
</style>
